<script setup>
import Dialog from '@/components/Dialog.vue'
import { ref, onMounted } from 'vue'
import api from '@/apis'
import config from '@/config'
import { useI18n } from 'vue-i18n'
import { useAccount, useWriteContract, useReadContract } from '@wagmi/vue'
import { erc20Abi, parseUnits, formatUnits } from 'viem'
import { showToast } from 'vant'
const { t } = useI18n()
const fullDialog = ref(null)
const stagingDialog = ref(null)
let payStatus = ref({
  0: '待还',
  1: '已还',
  2: '逾期'
})
// wagmi 状态
const { isConnected, address } = useAccount()
const { writeContractAsync } = useWriteContract()
//获取bsc商的usdt余额
const { data: balance } = useReadContract({
  address: config.contractAddress,
  abi: erc20Abi,
  functionName: 'balanceOf',
  args: [address]
})
//获取bsc商的usdt授权余额
const { data: allowance } = useReadContract({
  address: config.contractAddress,
  abi: erc20Abi,
  functionName: 'allowance',
  args: [address, config.contractAddress]
})
//期数选择
const selectId = ref(1)
//期数数据
const actions = ref([
  { text: '1', className: '_item', id: 1 },
  { text: '2', className: '_item', id: 2 },
  { text: '3', className: '_item', id: 3 },
  { text: '4', className: '_item', id: 4 },
  { text: '5', className: '_item', id: 5 },
  { text: '6', className: '_item', id: 6 },
  { text: '7', className: '_item', id: 7 },
  { text: '8', className: '_item', id: 8 },
  { text: '9', className: '_item', id: 9 },
  { text: '10', className: '_item', id: 10 }
])
const showPopover = ref(false)
//期数选择
let selectAction = ref({})
const onSelect = (e) => {
  selectId.value = e.id
  selectAction.value = currentStagingData._rawValue.repayments.find(item => item.period == e.id)

}

//借贷订单列表
let loanList = ref([])
onMounted(async () => {
  const res = await api.lending.loanList({
    page: 1,
    page_size: 10
  })
  loanList.value = res
  console.log(res);

})

//全额还款
let currentFullData = ref({})
let fullBalance = ref(0)
const openFull = async (item) => {
  if (item.status == 1) {
    showToast('暂无还款')
    return
  }
  resetDialog()
  currentFullData.value = item
  const res = await api.lending.repaymentFull({
    loan_id: item.id
  })
  fullBalance.value = res.amount
  fullDialog.value.open()
}
//分期还款
let currentStagingData = ref()
const openStaging = (item) => {
  if (item.status == 1) {
    showToast('暂无还款')
    return
  }
  resetDialog()
  currentStagingData.value = item
  selectAction.value = currentStagingData._rawValue.repayments.find(item => item.period == selectId.value)
  stagingDialog.value.open()
}

//重置所有弹窗数据
const resetDialog = () => {
  selectId.value = 1
  showPopover.value = false
  currentFullData.value = {}
  currentStagingData.value = {}
}

const handleStagingRepayment = async () => {
  let amount = selectAction._rawValue.repay_amount
  await chainPayment(amount)
}

//全额还款支付
const handleFullRepayment = async () => {
  await chainPayment(fullBalance.value)
}

//支付  number 需要支付的金额
let chainPayment = async (number) => {
  let amount = number
  const currentAllowance = allowance.value || 0
  //检测授权金额是否足够 不够先授权 够了直接转账
  if (currentAllowance < amount) {
    const remainingAmount = parseUnits((amount - currentAllowance).toString(), 18)
    await writeContractAsync({
      address: config.contractAddress,
      abi: erc20Abi,
      functionName: 'approve',
      args: [config.contractAddress, remainingAmount] // 授给bsc的usdt合约地址
    })
    Toast.success('授权成功')
  }
  await writeContractAsync({
    address: config.contractAddress,
    abi: erc20Abi,
    functionName: 'transfer',
    args: [config.receiptAddress, parseUnits(amount.toString(), 18)] // 转账给收款地址
  })
}


</script>
<template>
  <div class="container">
    <div class="body w-100%">
      <div class="body_top font-source text-[#fff] mb-20">
        <div class="title text-[22px] mb-10">{{ t('lending') }}</div>
        <div class="tips opacity-70 text-[12px] opacity-70">{{ t('lever_decs') }}</div>
      </div>
      <div class="body_card p-15 font-pingfang mb-15" v-for="(item, index) in loanList" :key="item.id">
        <div class="flex items-center justify-between mb-27">
          <div>
            <div class="text-[16px] text-[#fff] mb-8">{{ t('lending') }} #{{ index + 1 }}</div>
            <div class="flex items-center text-[10px]">
              <!-- <div class="p-6 px-10 text-[#fff] opacity-70 lever text-center">7×{{ t('lending_leverage') }}</div> -->
              <div
                class="p-6 px-10 text-[#00CE45] opacity-70 bg-[#00CE45]/10 text-center text-[#00CE45] rounded-[5px]">
                {{ payStatus[item.status] }}
                <!-- {{ t('lending_inProgress') }} -->
              </div>
            </div>
          </div>
          <div class="detail px-12 h-32 text-[#fff] text-[12px] font-source flex justify-center items-center">
            {{ t('lending_viewDetails') }}
          </div>
        </div>
        <div class="flex gap-80 items-center text-[#fff] text-[14px] mb-20">
          <div class="">
            <div class="mb-10 opacity-70">{{ t('lending_loanAmount') }}</div>
            <div class="">{{ item.amount }} USDT</div>
          </div>
          <div class="">
            <div class="mb-10 opacity-70">{{ t('lending_annualized') }}</div>
            <div class="">{{ item.interest_rate }} %</div>
          </div>
        </div>
        <div class="flex gap-80 items-center text-[#fff] text-[14px] mb-20">
          <div class="">
            <div class="mb-10 opacity-70">{{ t('lending_TotalAmountDue') }}</div>
            <div class="">{{ item.repay_amount }} USDT</div>
          </div>
          <div class="">
            <div class="mb-10 opacity-70">{{ t('lending_expirationDate') }}</div>
            <div class="">{{ item.end_time }}</div>
          </div>
        </div>
        <div class="now w-100% flex justify-between">
          <div class="now_label opacity-70">{{ t('lending_repaymentProgress') }}</div>
          <div class="now_value text-[#00FF95]">{{ item.progress_bar }}%</div>
        </div>
        <div class="w-100% h-9 rounded-full bg-[#4D5D73] progressbox">
          <div class="h-100% rounded-full progress w-75%" :style="{ width: `${item.progress_bar}%` }"></div>
        </div>
        <div class="now w-100% flex justify-between">
          <div class="now_label opacity-70">{{ t('lending_returned') }}: {{ item.over_repay }} USDT</div>
          <div class="now_value opacity-70">{{ t('lending_remaining') }}: {{ item.wait_repay }} USDT</div>
        </div>
        <div class="w-100% h-1 bg-[#fff] opacity-20 my-20"></div>
        <div class="flex items-center justify-between text-[14px]">
          <div class="w-50% h-36 bg-[#fff] text-[#182461] font-source flex items-center justify-center rounded-[8px]"
            @click="openFull(item)">
            {{ t('lending_fullRepayment') }}
          </div>
          <div
            class="w-50% h-36 text-[#fff] font-source flex items-center justify-center rounded-[8px] installment ml-14"
            @click="openStaging(item)">
            {{ t('lending_installmentRepayment') }}
          </div>
        </div>
      </div>
    </div>
    <Dialog ref="fullDialog" :title="t('lending_fullRepayment')" :cancelText="t('popup_cancel')"
      :confirmText="t('home_repayment')" @confirm="handleFullRepayment">
      <div class="pt-[16px] pb-[20px]">
        <div class="text-[36px] text-[#182461] font-roboto font-900 text-center mb-6">{{ fullBalance }} USDT</div>
        <div class="text-[#A2B0C3] text-[14px] text-center mb-20 font-pingfang">
          <!-- {{ t('lending_toBePaid') }} -->
          待还 {{ currentFullData.wait_repay }}USDT (含手续费{{ currentFullData.service_fee }}U)
        </div>
        <div class="text-[#000] text-[14px] font-source font-700 mb-8">{{ t('lending_amount') }}</div>
        <div class="h-46 p-16 flex items-center rounded-[7px] input mb-8 font-pingfang text-[14px]">
          <input type="number" class="text-[#78859D] w-100%" placeholder="" disabled v-model="fullBalance" />
          <div class="text-[#78859D] ml-6">USDT</div>
        </div>
        <div class="text-[#0074FF] text-[12px] font-pingfang">USDT{{ t('lending_balance') }}：{{ balance }}</div>
      </div>
    </Dialog>
    <Dialog ref="stagingDialog" :title="t('lending_installmentRepayment')" :cancelText="t('popup_cancel')"
      :confirmText="t('home_repayment')" @confirm="handleStagingRepayment">
      <div class="pt-[16px] pb-[20px]">
        <div class="text-[36px] text-[#182461] font-roboto font-900 text-center mb-6">{{ selectAction.repay_amount }}
          USDT</div>
        <div class="text-[#A2B0C3] text-[14px] text-center mb-20 font-pingfang">
          <!-- {{ t('lending_toBePaid') }} -->
          待还 {{ selectAction.repay_amount }}USDT (含手续费{{ selectAction.service_fee }}U)
        </div>
        <div class="flex flex-col gap-20">
          <div>
            <div class="text-[#000] text-[14px] font-source font-700 mb-8">{{ t('lending_selectIssues') }}</div>
            <div
              class="h-46 px-16 flex items-center justify-between rounded-[7px] input mb-8 font-pingfang text-[14px]">
              <div class="">{{actions.find(item => item.id == selectId).text}}{{ t('lending_phase') }}</div>
              <van-popover v-model:show="showPopover" :actions="actions" @select="onSelect" :show-arrow="false"
                :offset="[-30, -140]">
                <template #reference>
                  <div class="ml-6">
                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="12" viewBox="0 0 23 16" fill="none">
                      <path
                        d="M13.0915 14.9088C12.2911 15.9605 10.7089 15.9605 9.90848 14.9088L1.38655 3.71123C0.384508 2.39458 1.32348 0.5 2.97806 0.5H20.0219C21.6765 0.5 22.6155 2.39458 21.6135 3.71123L13.0915 14.9088Z"
                        fill="#78859D" />
                    </svg>
                  </div>
                </template>
                <template #action="{ action, index }">
                  <div class="text-[#78859D] text-[12px] text-center w-100%">
                    <span :class="action.id == selectId ? 'text-[#000000]' : ''">{{ action.text }}{{ t('lending_phase')
                    }}</span>
                  </div>
                </template>
              </van-popover>
            </div>
            <div class="text-[#0074FF] text-[12px] font-pingfang">
              {{ t('lending_everyMonth') }} {{ selectAction.repay_amount }}x{{ currentStagingData.repayments.length }} {{
                t('lending_phase') }}</div>
          </div>
          <div>
            <div class="text-[#000] text-[14px] font-source font-700 mb-8">{{ t('lending_InstallmentAmount') }}</div>
            <div class="h-46 px-16 flex items-center rounded-[7px] input mb-8 font-pingfang text-[14px]">
              <input type="number" class="text-[#78859D] w-100%" v-model="selectAction.repay_amount" disabled placeholder="" />
              <div class="text-[#78859D] ml-6">USDT</div>
            </div>
            <div class="text-[#0074FF] text-[12px] font-pingfang">USDT{{ t('lending_balance') }}：{{ balance }}</div>
          </div>
        </div>
      </div>
    </Dialog>
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;

  .body {
    min-height: calc(100vh - var(--van-nav-bar-height));
    background: url('@/static/imgs/lending/bg.png') no-repeat;
    background-size: 100% 100%;
    padding: 20px 15px;

    &_card {
      border-radius: 15px;
      border: 1px solid rgba(255, 255, 255, 0.5);
      background: rgba(255, 255, 255, 0.05);
      backdrop-filter: blur(3px);
    }
  }
}

.lever {
  border-radius: 5px;
  border: 1px solid #fff;
}

.detail {
  border-radius: 11px;
  border: 1px solid #fff;
  // box-shadow: 0 8px 32px 0 rgba(0, 60, 255, 0.34), 0 0 20px 0 rgba(163, 192, 255, 0.57) inset;
}

.now {
  color: #fff;
  font-family: 'PingFang SC';
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: normal;
}

.progressbox {
  margin-top: 9px;
  margin-bottom: 16px;

  .progress {
    background: linear-gradient(90deg, #1675fd 0%, #00fffb 100%);
  }
}

.installment {
  // border-radius: 16.564px;
  background: var(--5,
      radial-gradient(41.55% 42.54% at 52.19% 100%, #89a6ea 0%, #688eff 55.29%, #164bd6 100%));
  box-shadow: 0 0 7.826px 0 rgba(255, 255, 255, 0.5) inset,
    0 6.261px 25.043px 0 rgba(0, 60, 255, 0.34);
}

.input {
  background: #eceff5;

  input {
    background: rgba(65, 88, 140, 0);
    border: none;
    outline: none;
  }
}

// ._item{
//   border-bottom: 1px solid rgba($color: #000000, $alpha: .1);
// }
// ::deep .van-popover__action{
//   border-bottom: 1px solid rgba($color: #000000, $alpha: .1);
// }</style>
